package com.kakaxi.mybilibili.net;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.vincestyling.netroid.NetworkResponse;
import com.vincestyling.netroid.RequestQueue;
import com.vincestyling.netroid.request.ImageRequest;
import com.vincestyling.netroid.toolbox.ImageLoader;

import org.apache.http.protocol.HTTP;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * 图片加载管理器封装类
 * Created by kakaxi on 16/8/2.
 */
public class SelfImageLoader extends ImageLoader {

    /** app原始文件协议头 **/
    public static final String RES_ASSETS = "assets://";
    /** 存储卡协议头 **/
    public static final String RES_SDCARD = "sdcard://";
    /** 资源图片协议头 **/
    public static final String RES_DRAWABLE = "drawable://";
    /** http请求协议头 **/
    public static final String RES_HTTP = "http://";

    /** App原始文件管理器 **/
    private AssetManager mAssetManager;
    /** 资源管理器 **/
    private Resources mResources;


    public SelfImageLoader(RequestQueue queue, ImageCache imageCache, Resources resources, AssetManager assetManager) {
        super(queue, imageCache);
        mResources = resources;
        mAssetManager = assetManager;
    }

    @Override
    public ImageRequest buildRequest(String requestUrl, int maxWidth, int maxHeight) {
        ImageRequest request = null;
        if (requestUrl.startsWith(RES_ASSETS)) { // App原始文件读取
            request = new ImageRequest(requestUrl.substring(RES_ASSETS.length()), maxWidth, maxHeight) {
                @Override
                public NetworkResponse perform() {
                    try {
                        return new NetworkResponse(toBytes(mAssetManager.open(getUrl())), HTTP
                                .UTF_8);
                    } catch (IOException e) {
                        return new NetworkResponse(new byte[1], HTTP.UTF_8);
                    }
                }
            };
        } else if (requestUrl.startsWith(RES_DRAWABLE)) { // 资源文件读取
            request = new ImageRequest(requestUrl.substring(RES_DRAWABLE.length()), maxWidth, maxHeight) {
                @Override
                public NetworkResponse perform() {
                    try {
                        int resId = Integer.parseInt(getUrl());
                        Bitmap bitmap = BitmapFactory.decodeResource(mResources, resId);
                        return new NetworkResponse(bitmapToBytes(bitmap), HTTP
                                .UTF_8);
                    } catch (Exception e) {
                        return new NetworkResponse(new byte[1], HTTP.UTF_8);
                    }
                }
            };
        } else if (requestUrl.startsWith(RES_SDCARD)) { // sd存储卡读取
            request = new ImageRequest(requestUrl.substring(RES_SDCARD.length()), maxWidth, maxHeight) {
                @Override
                public NetworkResponse perform() {
                    try {
                        return new NetworkResponse(toBytes(new FileInputStream(getUrl())), HTTP
                                .UTF_8);
                    } catch (IOException e) {
                        return new NetworkResponse(new byte[1], HTTP.UTF_8);
                    }
                }
            };
        } else if (requestUrl.startsWith(RES_HTTP)) { // http读取
            request = new ImageRequest(requestUrl, maxWidth, maxHeight);
        }

        // 设置缓存
        makeRequestCache(request);
        return request;
    }

    /**
     * 设置请求缓存的时间
     * @param request 要设置缓存的请求
     */
    public void makeRequestCache(ImageRequest request) {
        request.setCacheExpireTime(TimeUnit.MINUTES, 10);
    }


    /**
     * 把文件的二进制写入内存再取出二进制数组
     * @param is 输入流
     * @return
     * @throws IOException
     */
    public static byte[] toBytes(InputStream is) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();

        return buffer.toByteArray();
    }

    /**
     * 图片转换为二进制数组
     * @param bm 图片
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

}
